package com.zxj.job.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zxj.common.core.contains.CacheConstants;
import com.zxj.common.core.contains.Constants;
import com.zxj.common.redis.service.RedisService;
import com.zxj.job.mapper.user.UserSubmitMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
@RequiredArgsConstructor
public class QuestionXxlJob {
    private final UserSubmitMapper userSubmitMapper;
    private final RedisService redisService;

    @XxlJob("questionHostHandler")
    public void questionHostHandler() {
        log.info("刷新热门题目缓存: {}", LocalDateTime.now());
        // 分页功能
        PageHelper.startPage(Constants.HOST_QUESTION_LIST_START, Constants.HOST_QUESTION_LIST_END);
        List<Long> questionIds = userSubmitMapper.selectHostQuestionList();
        log.info("热门题目ID: {}", questionIds);
        refreshHotQuestionList(questionIds);
    }

    /**
     * 刷新热门题目列表
     * @param hotQuestionIdList 热门题目ID列表
     */
    public void refreshHotQuestionList(List<Long> hotQuestionIdList) {
        if (CollectionUtil.isEmpty(hotQuestionIdList)) {
            return;
        }
        redisService.deleteObject(CacheConstants.QUESTION_HOST_LIST); // 删除原有的热门题目列表
        redisService.rightPushAll(CacheConstants.QUESTION_HOST_LIST, hotQuestionIdList); // 重新插入热门题目列表
    }
}
